package com.deercrowing.takeaway.controller.user;


import com.alibaba.fastjson.JSON;
import com.deercrowing.takeaway.common.constant.TokenConstant;
import com.deercrowing.takeaway.common.model.Result;
import com.deercrowing.takeaway.common.properties.AppProperties;
import com.deercrowing.takeaway.common.util.JwtUtil;
import com.deercrowing.takeaway.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONException;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import com.deercrowing.takeaway.entity.UsersEntity;
import com.deercrowing.takeaway.service.UsersService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户表(Users)表控制层
 *
 * @author guoyongxiang
 * @since 2024-07-25 10:38:44
 */
@Slf4j
@Validated
@RestController
@RequestMapping("user/users")
public class UsersController {
    /**
     * 服务对象
     */
    @Autowired
    private UsersService usersService;

    @Autowired
    private AppProperties appProperties;

    @PostMapping("/login")
    public ResponseEntity login(@RequestBody String jsonCode) throws JSONException {
        Map<String,String> map = (Map)JSON.parse(jsonCode);
        log.info("微信用户登录：{}",map.get("code"));

        //微信登录
        UsersEntity usersEntity = usersService.wxLogin(map.get("code").toString());

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(TokenConstant.USER_ID,usersEntity.getId());
        String token = JwtUtil.BuildToken(appProperties.getEncodedSecretKey(), appProperties.getLifeSpan(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(usersEntity.getId())
                .openid(usersEntity.getOpenid())
                .token(token)
                .build();
        return ResponseEntity.ok(Result.OK(userLoginVO));
    }
}

